<?php
declare (strict_types = 1);

namespace app\index\controller;
use think\facade\View;
use think\facade\Db;
use think\captcha\facade\Captcha;

use app\common\model\Order as OrderModel;
use app\common\model\Lists as ListsModel;

use app\admin\validate\Order as validateOrder;

//use alipay\aop\AopClient;
//use alipay\aop\request\AlipayTradePagePayRequest;

use alipaymobile\aop\AopClient;
use alipaymobile\aop\request\AlipayTradePagePayRequest;
//
use alipaymobile\aop\AlipayTradeService;
use alipaymobile\aop\AlipayTradeWapPayContentBuilder;

class Alipay extends Base
{

    private $aop;
    private $alipay_config;


    public function  __construct() {
        parent::__construct();

        $webconfig = DB::name("webconfig")->where('vargroup','=',6)->select();
        $webconfig_arr = [];
        foreach($webconfig as $v){
            $webconfig_arr[$v['varname']] = $v['varvalue'];
        }
        $arr = [
            'app_id' => $webconfig_arr['cfg_alipay_app_id'],//app_id
            'notify_url'=>$webconfig_arr['cfg_alipay_notify_url'],//异步通知
            'merchant_private_key' => $webconfig_arr['cfg_alipay_private_key'],//商户私钥
            'gatewayUrl' => $webconfig_arr['cfg_cfg_alipay_public_key'],//网关 https://openapi.alipay.com/gateway.do
            'alipay_public_key' => $webconfig_arr['cfg_alipay_app_id'],//公钥
            'return_url' => $webconfig_arr['cfg_alipay_return_url'],//同步通知
            'charset' => "UTF-8",//编码格式
            'sign_type' => "RSA2",//签名方式(在你生成秘钥的时候，选择的加密方式)
            'log_path' => "",//日志路径

        ];
        $this->alipay_config = $arr;


        /*$aop = new AopClient();
        $aop->gatewayUrl = $this->alipay_config['gatewayUrl'];
        $aop->appId = $this->alipay_config['app_id'];
        $aop->signType = 'RSA2';
//        $aop->method = 'alipayTradePagePay';
        //$aop->method = 'AlipayTradeWapPay';
        //$aop->charset = 'utf-8';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';

        $aop->alipayrsaPublicKey = $this->alipay_config['alipay_public_key'];
        $aop->rsaPrivateKey      = $this->alipay_config['merchant_private_key'];*/

        $aop = new AopClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $this->alipay_config['app_id'];
        $aop->rsaPrivateKey = $this->alipay_config['merchant_private_key'];
        $aop->alipayrsaPublicKey = $this->alipay_config['alipay_public_key'];
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';

        $this->aop = $aop;
    }



    public function pay2(){


        Db::startTrans();
        try {
            /*$aop = new AopClient;
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            $aop->appId = $this->alipay_config['app_id'];
            $aop->rsaPrivateKey = $this->alipay_config['merchant_private_key'];
            $aop->alipayrsaPublicKey = $this->alipay_config['alipay_public_key'];
            $aop->signType = 'RSA2';
            $aop->postCharset = 'utf-8';
            $aop->format = 'json';*/

            $param = input('param.');
            $order_id = $param['order_id'];
            $ord = DB::name("order") -> where('id','=',$order_id)->find();
            $biz_content = json_encode([
                'out_trade_no'=> $ord['order_sn'],
                'product_code'=> 'FAST_INSTANT_TRADE_PAY',
                'total_amount'=> $ord['price'],
                'subject'=> $ord['title'],
            ]);
            /** 实例化具体API对应的request类，类名称和接口名称对应，当前调用接口名称：alipay.trade.wap.pay（手机网站支付接口）**/
            $request = new AlipayTradePagePayRequest;

            /*$orderSn = rand(1000,9999);
            $amount = 0.01;
            $productName = '测试';
            $biz_content = json_encode([
                'out_trade_no'=> $orderSn,
                'product_code'=> 'FAST_INSTANT_TRADE_PAY',
                'total_amount'=> $amount,
                'subject'=> $productName,
            ]);*/

            /** 设置业务参数 **/
            $request->setBizContent($biz_content);
            $request->setReturnUrl("http://hzsczx.com/index/order/successpage");
            $request->setNotifyUrl("http://hzsczx.com/index/Alipay/notify_url");

            /** 调用SDK生成支付链接，可在浏览器打开链接进入支付页面 **/
            $result = $this->aop->pageExecute($request, "get");

            //$this->redirect($result);

            /**第三方调用（服务商模式），传值app_auth_token后，会收款至授权token对应商家账号，如何获传值app_auth_token请参考文档：https://opensupport.alipay.com/support/helpcenter/79/201602494631 **/
            //$result = $aop->pageExecute($request,'get',"传入获取到的app_auth_token值");
            Db::commit();
            return $result;
        }catch (\Exception $e){
            Db::rollback();
            // 进行错误处理
            //return $this->error($e->getMessage());
            return dyajaxReturn(0,$e->getMessage());
        }
    }


    /*public function pay(){
        $param = input('param.');
        if(!isset($param['order_id']) && $param['order_id']==''){
            $this->error("缺少关键参数order_id");
        }
        $order_id = $param['order_id'];
        $OrderModel = new OrderModel();
        $ord = $OrderModel -> where('id','=',9)->find();
        $biz_content = json_encode([
            'out_trade_no'=> $ord['order_sn'],
            'product_code'=> 'FAST_INSTANT_TRADE_PAY',
            'total_amount'=> $ord['price'],
            'subject'=> $ord['title'],
            'timeout_express'=>'30m',
        ]);

        $payRequest= new AlipayTradePagePayRequest();

        $payRequest->setReturnUrl("http://hzsczx.com/index/users/user_center_order");
        $payRequest->setNotifyUrl("http://hzsczx.com/index/Alipay/notify_url");
        $payRequest->setBizContent($biz_content);
        $response = $this->aop->sdkExecute($payRequest);
        echo '<a href="'.'https://openapi.alipay.com/gateway.do?'.$response.'">';
    }*/





    public function notify_url(){

        $out_trade_no = $_POST['out_trade_no']; //商户订单号
        $trade_no = $_POST['trade_no']; //支付宝交易号
        $trade_status = $_POST['trade_status']; //交易状态

        //返回值里面$_POST['trade_status']是支付结果的信息，我给贴下面了，可以根据自己需求设置回调值
        if ($trade_status == 'TRADE_SUCCESS') {
            //我这里设置的是，如果返回值是支付成功，那么就把这个订单状态给改成6
            //out_trade_no这个是返回的订单号
            Db::name('order')
                ->where(['order_sn'=>$out_trade_no])
//                        ->where('id','=',2)
                ->update([
                    'pay_status'=>3,
                    'pay_time'=>time(),
                    'transaction_id'=>$trade_no
                ]);
            //注意，一定要echo 一个success，因为支付宝没有在页面看到success的话，还会继续发回调信息
            echo 'success';
        }

        //使用rsaCheckV1方法检验回调数据是否合法，最后的返回值是一个布尔值
        //按照我的直接写就行，中间的参数，它要的是公钥的路径，但是我再上面给公钥设置了值，所以直接填空就行，他就会找字符串的公钥
        /*$aop = new AopClient;
        $aop->alipayrsaPublicKey = $this->alipay_config['alipay_public_key'];
        $check=$aop->rsaCheckV1($_POST,'',$_POST['sign_type']);
        //这里判断一下$check
        if($check){
            $out_trade_no = $_POST['out_trade_no']; //商户订单号
            $trade_no = $_POST['trade_no']; //支付宝交易号
            $trade_status = $_POST['trade_status']; //交易状态

            //返回值里面$_POST['trade_status']是支付结果的信息，我给贴下面了，可以根据自己需求设置回调值
            if ($trade_status == 'TRADE_SUCCESS') {
                //我这里设置的是，如果返回值是支付成功，那么就把这个订单状态给改成6
                //out_trade_no这个是返回的订单号
                Db::name('order')
                    ->where(['order_sn'=>$out_trade_no])
//                        ->where('id','=',2)
                    ->update([
                        'pay_status'=>1,
                        'transaction_id'=>$trade_no
                    ]);
                //注意，一定要echo 一个success，因为支付宝没有在页面看到success的话，还会继续发回调信息
                echo 'success';
            }
        }*/
    }
}
